package com.liuyz.udp_;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UDP数据交互 {

    // 发送端：先发送数据再接收数据
    @Test
    public void sender() throws IOException {
        String data = "hello,明天吃火锅";

        DatagramSocket datagramSocket = new DatagramSocket(9998);
        // 发送端：通过sender的9998端口发送数据到9999端口上
        DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], 1024, new InetSocketAddress("127.0.0.1", 9999));

        datagramPacket.setData(data.getBytes());
        datagramSocket.send(datagramPacket);

        // 接收端：通过sender的9998端口接收数据
        datagramPacket = new DatagramPacket(new byte[1024], 1024);
        datagramSocket.receive(datagramPacket);

        byte[] dataArr = datagramPacket.getData(); // getData()：获取数据字节
        System.out.println(new String(dataArr, 0, datagramPacket.getLength())); // getLength()：获取数据字节长度

        // 关闭socket
        datagramSocket.close();
    }

    // 接收端：先接收数据再发送数据
    @Test
    public void receiver() throws IOException {
        String data = "ok,明天见";
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        // 接收端：通过receiver的9999端口接收数据
        DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], 1024);

        datagramSocket.receive(datagramPacket);
        byte[] dataArr = datagramPacket.getData(); // getData()：获取数据字节
        // dataArr.length = 1024;
        System.out.println(new String(dataArr, 0, datagramPacket.getLength())); // getLength()：获取数据字节长度

        // 发送端：通过receiver的9999端口发送数据到9998端口上
        datagramPacket = new DatagramPacket(new byte[1024], 1024, new InetSocketAddress("127.0.0.1", 9998));
        datagramPacket.setData(data.getBytes());
        datagramSocket.send(datagramPacket);

        // 关闭socket
        datagramSocket.close();
    }

}
